package org.iabako.client.ui.page.business.sale;

import com.google.gwt.user.client.Timer;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.tools.Messages;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.form.business.sale.make.SaleMakeForm;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.business.Sale;

/**
 * Created by jose on 20/07/14.
 */
public class SaleMake extends SaleMakeForm {

    public SaleMake(final AbstractForm abstractForm) {
        super(PageConfigEnum.SaleMake, "");

        final String[] params = NavigationController.getInstance().getParams();
        boolean isSaleFromQuote = abstractForm instanceof QuoteMake || abstractForm instanceof QuoteModify;

        if (abstractForm instanceof SaleGoTo && params != null && params[0] != null) {
            //This is a draft then
            contentPanel.setVisible(false);
            waitIconPanel.setVisible(true);

            saleServiceAsync.getById(Long.parseLong(params[0]), new IabakoAsyncCallback<AbstractEntity>() {
                public void onSuccess(AbstractEntity result) {
                    if (result == null) {
                        NavigationController.getInstance().closePopup(simplePopup);
                        super.onSuccess(result);
                        return;
                    }
                    restoreDraft((Sale) result);
                    super.onSuccess(result);
                }
            });

        } else if (!isSaleFromQuote && params != null && params[0] != null) {
            //This is sale en masse
            popup.popupTitle.setText(Messages.getLabel("sales_en_masse_title"));
            activateSaleEnMasse(params[0]);
            //This field is not used in server side but necessary in UIValidation (because of hibernate automatic validation)
            saleMakeConfirmation.number.setValue("000000");

        }
        if (isSaleFromQuote) {
            this.parentForm = abstractForm;
            popup.timerAfterClosePopupAnimation = new Timer() {
                public void run() {
                    NavigationController.getInstance().closePopup(simplePopup);
                    if (parentForm != null) {
                        NavigationController.getInstance().goTo(parentForm);
                    }
                }
            };
        } else {
            //This is normal first access
            saleServiceAsync.getNextAvailableId(new IabakoAsyncCallback<String>() {
                public void onSuccess(String result) {
                    saleMakeConfirmation.number.setValue(result);
                    super.onSuccess(result);
                }
            });
        }
    }
}
